package cn.dglydrpy.study.j2ee.servlet.day08;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.dglydrpy.study.j2ee.jdbc.utils.DBUtil;

/**
 * Servlet implementation class BmiServlet2  //新建的时候右键servlet 设置相关的参数，自动生成配置文件
 */
/* 要求：
 * 1.将19（min） 25(max) 写入初始化配置 
 * 2.使用后缀匹配(*.bmi)
 * 
 */
public class BmiServlet2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private int min;
	private int max;

	
	public void init() throws ServletException {//读配置文件放入初始化里只读一次
		ServletConfig servletConfig = getServletConfig();
		min = Integer.parseInt(servletConfig.getInitParameter("min"));
		max = Integer.parseInt(servletConfig.getInitParameter("max"));	
	}

//可通过重写doGet()或doPost()来达到同样的功能
//	protected void service(HttpServletRequest request, HttpServletResponse response)
//			throws ServletException, IOException {}
	
	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		// 对浏览器提交过来的数据进行utf-8格式的解码,这句话要放在所有request.getParameter()之前且只对post请求有效
		request.setCharacterEncoding("utf-8");
		String url = request.getRequestURI();
		String path = url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
		if ("/tj".equals(path)) {
			double height = Double.parseDouble(request.getParameter("height"));
			double weight = Double.parseDouble(request.getParameter("weight"));

			String[] interests = request.getParameterValues("interest");
			System.out.println(Arrays.toString(interests));

			double bmi = 10000 * weight / height / height;

			Connection conn = null;
			PreparedStatement ps = null;
			try {
				conn = DBUtil.getConn();
				String sql = "insert into bmi values(null,?,?,?)";
				ps = conn.prepareStatement(sql);
				ps.setDouble(1, height);
				ps.setDouble(2, weight);
				ps.setDouble(3, bmi);

				ps.executeUpdate();

			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			} finally {
				try {
					DBUtil.close(conn, ps, null);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			String msg = "体重正常，请继续保持！";
			if (bmi > max) {
				msg = "体重偏重！";
			} else if (bmi < min) {
				msg = "体重偏轻！";
			}

			request.setAttribute("msg", msg);
			request.getRequestDispatcher("bmi.jsp").forward(request, response);
		}
	}
}
